<?php
namespace app\admin\controller;

use think\Db;
use think\Log;
use Qiniu\Auth as QnAuth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use app\home\model\CreditRecord;

use app\home\model\Member;

class Chat extends Base{

    public function index(){
        if(request()->isAjax()){
            $ids = params_array('ids');
            if(!check_array($ids)){
                message('请选择要删除的反馈','','error');
            }
            $status = \app\admin\model\Chat::deleteByIds($ids);
            if(!$status){
                message('删除失败','','error');
            }
            message("删除成功",'reload','success');
        }
        $where=[];

        $params = request()->param();
        if(!empty($params['uid'])){
            $where['uid'] =$params['uid'];
        }
        if(!empty($params['cid'])){
            $where['cid'] =$params['cid'];
        }
        if(!empty($params['task_id'])){
            $where['task_id'] =$params['task_id'];
        }
        $total = \app\admin\model\Chat::getCount($where);
      //  $list = \app\admin\model\Chat::getPagination($where, 15, $total, "id DESC");
        $list=db('chat_reply')->where($where)->order('id desc')->paginate(15);
        $task_model=db('task');
        $member_model=db('member');
//dump($list);die;
        $datas=[];
        foreach($list as $k=>$v){
            $d=$v;
            $d['title']=$task_model->where('id',$v['task_id'])->value('title');
            $datas[]=$d;
        }

        $pager = $list->render();
        return $this->fetch(__FUNCTION__, [
            'list' => $datas,
            'pager' => $pager,
            'total' => $total
        ]);
    }
    
    
      public function groupchat(){
        if(request()->isAjax()){
            $ids = params_array('ids');
            if(!check_array($ids)){
                message('请选择要删除的内容','','error');
            }
           $status=db('groupchat')->where(['id'=>['in',$ids]])->delete();
            if(!$status){
                message('删除失败','','error');
            }
            message("删除成功",'reload','success');
        }
        $where=[];

        $params = request()->param();
        if(!empty($params['uid'])){
            $where['uid'] =$params['uid'];
        }

        $total = \app\admin\model\Chat::getCount($where);
      //  $list = \app\admin\model\Chat::getPagination($where, 15, $total, "id DESC");
        $list=db('groupchat')->where($where)->order('id desc')->paginate(15);

        
        $pager = $list->render();
        return $this->fetch(__FUNCTION__, [
            'list' => $list,
            'pager' => $pager,
            'total' => $total
        ]);
    }
    
    
    
    
    
    
    public function upimg(){
    $file = request()->file('upimg');
    $filePath = $file->getRealPath();
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        // 上传到七牛后保存的文件名
        $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
        require_once APP_PATH . '/../vendor/qiniu/autoload.php';
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = config('ACCESSKEY');
        $secretKey = config('SECRETKEY');
        // 构建鉴权对象
        $auth = new QnAuth($accessKey, $secretKey);
        // 要上传的空间
        $bucket = config('BUCKET');
        $domain = config('DOMAIN');
        $token = $auth->uploadToken($bucket);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        $data['img'] = 'http://'.$domain.'/' . $ret['key'];
        echo json_encode($data);

  }


    public function post(){
        $id = params('id');
        $item = [];

        $item = db('chat_reply')->find($id);
        $list = db('chat_reply')->where('parent_id',$item['id'])->select();


        return $this->fetch(__FUNCTION__,[
            'item' => $item,
            'list' => $list,
        ]);
    }

    public function save() {
        $params = request()->post();
        if(empty($params['content']) && empty($params['img'])){
            message('请输入您需要反馈的内容','','error');
        }

        $params['parent_id'] = isset($params['parent_id']) ? intval($params['parent_id']) : 0;

        $request = request();
        $id=input('id');
        $chat_info=db('chat_reply')->find($id);

        $status3 =db('chat_reply')->insert([
            'task_id'=>$chat_info['task_id'],
            'cid'=>$chat_info['cid'],
            'uid' => 0,
            'content' => $params['content'],
            'img' => $params['img'],
            'avatar' => 'http://10.168.1.202/uploads/20210730/e1d1e063b7fae7a0c98ea97d1f12fac6.png',
            'nickname' => '管理员',
            'parent_id' => $params['id'],
            'create_time' => date('Y-m-d H:i:s'),

        ]);
        if(!$status3){
            message('反馈失败：-1','','error');
        }


        message('反馈成功','reload','success');
    }

    public function lists(){
        if(request()->isAjax()){
            $ids = params_array('ids');
            if(!check_array($ids)){
                message('请选择要删除的反馈','','error');
            }
            $status = db('chat')->where(['id'=>['in',$ids]])->delete();
            if(!$status){
                message('删除失败','','error');
            }
            message("删除成功",'reload','success');
        }
        $where=[];

        $params = request()->param();
        if(!empty($params['uid'])){
            $where['uid'] =$params['uid'];
        }
        if(!empty($params['task_id'])){
            $where['task_id'] =$params['task_id'];
        }
        $status='';
         if(!empty($params['status'])){
            $where['status'] =$params['status'];
            $status =$params['status'];
        }
        $total = db('chat')->where($where)->count();
      //  $list = \app\admin\model\Chat::getPagination($where, 15, $total, "id DESC");
        $list=db('chat')->where($where)->order('id desc')->paginate(15);
        $task_model=db('task');
        $member_model=db('member');
//dump($list);die;
        $datas=[];
        foreach($list as $k=>$v){
            $d=$v;
            $d['title']=$task_model->where('id',$v['task_id'])->value('title');
            $datas[]=$d;
        }

        $pager = $list->render();
        return $this->fetch(__FUNCTION__, [
            'list' => $datas,
            'pager' => $pager,
            'total' => $total,
            'status' => $status,
        ]);
    }
    //投诉列表
    public function complaintlist(){
    	$params = request()->param();
    	$where=[];
    	if(!empty(input('uid'))){
            $where['uid'] =input('uid');
        }
        if(!empty(input('task_id'))){
            $where['task_id'] =input('task_id');
        }
        if(input('status') !=''){
            $where['status'] = input('status');
        }
    	$list = db('complaint')->where($where)->order('id desc,status asc')->paginate(15,false,['query'=>input()]);
    	$pager = $list->render();
    	return $this->fetch(__FUNCTION__, [
            'list' => $list,
            'pager' => $pager,
        ]);
    }
    //投诉详情
    public function complaint(){
    	$complaint = db('complaint')->where('id',input('id'))->find();
    	$detail = db('task')->where('id',$complaint['task_id'])->field('detail')->find();
    	$task_join = db('task_join')->where('id',$complaint['join_id'])->field('check_text_content,check_text_content2')->find();
    	$guzhuimgs = db('task_operate_steps')->where('task_id',$complaint['task_id'])->where('type',2)->field('image')->select();
    	$zhuankeimgs = db('task_join')->where('id',$complaint['join_id'])->field('thumbs')->find();
    	$zhuankeimgs = unserialize($zhuankeimgs['thumbs']);
    	$list = db('complaint_reply')->where('tid',input('id'))->select();
		if(request()->isAjax()){
			$data['content'] = input('content');
			$data['is_admin'] = 1;
			$data['tid'] = input('id');
			$res = db('complaint_reply')->insert($data);
			if($res){
                message("成功",'reload','success');
            }else{
            	message('失败','','error');
            }
		}
    	return $this->fetch(__FUNCTION__, [
            'list' => $list,
            'complaint' => $complaint,
            'zhuankeimgs' =>$zhuankeimgs,
            'guzhuimgs' => $guzhuimgs,
            'detail'	=> $detail,
            'task_join' => $task_join

        ]);
    }
    //投诉通过
    public function compass(){
    	$complaint_info = db('complaint')->where('id',input('id'))->find();
    	$task_info = db('task')->where('id',$complaint_info['task_id'])->find();
    	if($complaint_info['status'] != 0){
    		message("已经裁决的不可更改",'reload','error');
    	}
    	db()->startTrans();
    	//投诉状态改为胜出
    	$complaint_data['status'] = 1;
    	$complaint_data['over_time'] = time();
    	$complaint_res = db('complaint')->where('id',input('id'))->update($complaint_data);
    	//根据投诉类型的不同去做处理
    	if($complaint_info['type']==2){
    		//雇主投诉成功
    		//任务状态设置成已过期，解除申诉，本身已经为不通过状态
    		$task_join_data['delflag'] = 2;
	    	$task_join_data['is_fanhuan'] = 1;
	    	$task_join_data['is_shensu'] = 0;
	    	$task_join_data['has_tousu'] = 1;
	    	$task_join_res = db('task_join')->where('id',$complaint_info['join_id'])->update($task_join_data);
	    	//给雇主把已加入票数减去1
	    	$task_res = db('task')->where('id',$complaint_info['task_id'])->setDec('join_num');
	    	//明天把助手函数事物搞上去
		    if($complaint_res  && $task_join_res && $task_res){
		    	db()->commit();
		    	message("成功",'reload','success');
		    }else{
		    	db()->rollback();
		    	message("失败",'reload','error');
		    }
    	}else{
    		//赚客投诉成功
    		//用户加钱、积分、猫宠所需积分，免费会员完成任务度以及打卡
	    	$userinfo = db('member')->where('uid',$complaint_info['uid'])->find();
	    	if($userinfo['partition_status']==1){
		            $jackpot = db('jackpot')->where('uid',$userinfo['uid'])->where('today_time',date('Ymd'))->find();
		            if($jackpot['num']>$userinfo['partition_num']){
		                $member_data['partition_num'] = $userinfo['partition_num']+1;
		            }
		            if($jackpot['num']==$userinfo['partition_num']+1){
		                	$member_data['partition_status']=2;
		            }
		    }
		    $member_data['over_task_num'] = $userinfo['over_task_num']+1;
		    $member_data['credit2'] = $userinfo['credit2']+$task_info['unit_price'];
		    if($task_info['give_credit1']>0){
		    	$member_data['pet_need_credit'] = $userinfo['pet_need_credit']+$task_info['give_credit1'];
	        	$member_data['credit1'] = $userinfo['credit1']+$task_info['give_credit1'];
		    }
		    $member_res = db('member')->where('uid',$userinfo['uid'])->update($member_data);
		    if($task_info['unit_price']>0){
		    	 CreditRecord::addInfo([
                'uid' => $userinfo['uid'],
                'type' => 'credit2',
                'num' => $task_info['unit_price'],
                'title' => '审核任务',
                'remark' => "任务" . $complaint_info['task_id'] . "审核成功，奖励".$task_info['unit_price']."元。",
                'create_time' => TIMESTAMP
            ]);
		    }
		    if($task_info['give_credit1']>0){
		    	 CreditRecord::addInfo([
                'uid' => $userinfo['uid'],
                'type' => 'credit1',
                'num' => $task_info['give_credit1'],
                'title' => '审核任务',
                'remark' => "任务" . $complaint_info['task_id'] . "审核成功，奖励".$task_info['give_credit1']."积分。",
                'create_time' => TIMESTAMP
            ]);
		    }
		    //任务状态设置成完成，申诉解除
		    $task_join_data['status'] = 3;
		    $task_join_data['is_shensu'] = 0;
		    $task_join_res = db('task_join')->where('id',$complaint_info['join_id'])->update($task_join_data);
		    //明天把助手函数事物搞上去
		    if($complaint_res && $member_res && $task_join_res){
		    	
		    	
		    	
//给上级和上上级发奖励
task_reward($userinfo,$task_info);



		
		
		//发红包
$params['id']=$complaint_info['task_id'];
$joinInfo['uid']=$userinfo['uid'];

		$redpackage=\db('redpackage')->where(['task_id'=>$params['id']])->find();


		
		if($redpackage && !$redpackage['is_over']){
				$has_send_money=\db('redpackage_record')->where(['task_id'=>$params['id'],'uid'=>['neq',0]])->sum('money');
				$has_send_number=\db('redpackage_record')->where(['task_id'=>$params['id'],'uid'=>['neq',0]])->count();
	
				if($has_send_money <$redpackage['money']){
					
					//要发的红包
					$send_info=\db('redpackage_record')->where(['task_id'=>$params['id'],'uid'=>['eq',0]])->order('redpackage_record_id asc')->find();
					
					$left_money=$redpackage['money']-$has_send_money;

					if($send_info && $left_money>0){
						
							//是否最后一个用户
							if( ($has_send_number+1) == $redpackage['number'] ){
								\db('redpackage')->where(['task_id'=>$params['id']])->setField('is_over',1);
							}
							
							$get_money=$send_info['money'];
							
					
							
						     $credit2 = $userinfo['credit2']+$get_money;
					    
					       // $res1 = \db('member')->where(['uid'=>$joinInfo['uid']])->data(['credit2'=>$credit2])->update();
					          
					          $res1 = Member::updateCreditById($joinInfo['uid'], 0, $get_money);
					          
					            if(!$res1){
						            Db::rollback();
						            message('操作失败:-3','','error');
						        }
		
		
					        $creditdata = array(
					            'uid'=>$joinInfo['uid'],
					            'type'=>'credit2',
					            'num'=>'+'.$get_money,
					            'title'=>'完成任务获得红包',
					            'remark'=>'完成任务'.$params['id'].'获得红包'.$get_money,
					            'create_time'=>time(),
					            'balance'=>$credit2,    //追加后的余额
					        );
					        $res3 = \db('credit_record')->data($creditdata)->insert();
					        if(!$res3){
					            Db::rollback();
					            message('审核失败:-5','','error');
					        }
					        
					        $send_info['uid']=$joinInfo['uid'];
					        $send_info['add_time']=time();
					        
					       $res4 = \db('redpackage_record')->data($send_info)->update();
					        if(!$res4){
					            Db::rollback();
					            message('审核失败:-6','','error');
					        }
					}
				        
				        
				        
				}
			        
		
		}


		
		
		
		    	
		    	
		    	
		    	
		    	
		    	
		    	db()->commit();
		    	message("成功",'reload','success');
		    }else{
		    	db()->rollback();
		    	message("失败",'reload','error');
		    }
    	}
    	
    	
	    
    }
    //投诉不通过
    public function comnopass(){
    	$complaint_info = db('complaint')->where('id',input('id'))->find();
    	if($complaint_info['status'] != 0){
    		message("已经裁决的不可更改",'reload','error');
    	}
    	$task_info = db('task')->where('id',$complaint_info['task_id'])->find();
    	db()->startTrans();
    	//投诉状态改为失败
    	$complaint_data['status'] = 2;
    	$complaint_data['over_time'] = time();
    	$complaint_res = db('complaint')->where('id',input('id'))->update($complaint_data);
    	//根据投诉类型的不同去做处理，雇主投诉失败不做处理
    	if($complaint_info['type']==1){
    		//任务状态设置成未完成，申诉解除,设置已返还
		    $task_join_data['status'] = 4;
		    $task_join_data['delflag'] = 2;
		    $task_join_data['is_fanhuan'] = 1;
		    $task_join_data['is_shensu'] = 0;
		    $task_join_data['has_tousu'] = 1;
		    $task_join_res = db('task_join')->where('id',$complaint_info['join_id'])->update($task_join_data);
		    //给雇主把已加入票数减去1
		    $task_res = db('task')->where('id',$complaint_info['task_id'])->setDec('join_num');
		    //明天把助手函数事物搞上去
		    if($complaint_res && $task_res && $task_join_res){
		    	db()->commit();
		    	message("成功",'reload','success');
		    }else{
		    	db()->rollback();
		    	message("失败",'reload','error');
		    }
    	}else{
		    $task_join_data['is_shensu'] = 0;
		  
		    $task_join_res = db('task_join')->where('id',$complaint_info['join_id'])->update($task_join_data);
    		if($complaint_res){
    			db()->commit();
		    	message("成功",'reload','success');
		    }else{
		    	db()->rollback();
		    	message("失败",'reload','error');
		    }
    	}
    
	    
    }


}











